package cn.pzaily.orange.core.utils;

import cn.pzaily.orange.core.utils.convert.CharseKit;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @PackageName: cn.pzaily.orange.core.utils
 * @Description:
 * @Author: Pang
 * @Date: 2021-05-11 22:52
 */
public class FileUtils {

    /**
     * 文件的下载
     * @param response
     * @param file
     * @param newFileName
     */
    public static void downloadFile(HttpServletResponse response, File file, String newFileName) {
        BufferedOutputStream bufferedOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String(newFileName.getBytes("ISO-8859-1"), CharseKit.UTF_8));

            bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());

            bufferedInputStream = new BufferedInputStream(new FileInputStream(file.getAbsoluteFile()));

            int length = 0;

            byte[] temp = new byte[1 * 1024 * 10];
            while ((length = bufferedInputStream.read(temp)) != -1) {
                bufferedOutputStream.write(temp, 0, length);
            }
            bufferedOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(bufferedInputStream);
            IOUtils.close(bufferedOutputStream);
        }
    }

    /**
     * 文件的删除
     * @param file
     */
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteFile(f);
            }
        }
        file.delete();
    }
}
